<template>
	<div>
		<div class="toolbar mt-2">
			<a-form ref="searchRef" layout="inline" :model="searchState" @finish="current=1;expandedRowKeys=[];loading=true;">
				<a-form-item label="名称">
					<a-input v-model:value="searchState.name" placeholder="请输入" allow-clear></a-input>
				</a-form-item>

				<a-form-item>
					<a-space>
						<a-select v-model:value="searchState.status" style="width: 120px">
							<a-select-option v-for="status in flowStatus" :key="status.status" :value="status.status">{{ status.name }}</a-select-option>
						</a-select>
						<a-button type="primary" html-type="submit">
							<search-outlined />搜索
						</a-button>

						<a-button @click="addIndustry">
							<plus-outlined />添加
						</a-button>
					</a-space>
				</a-form-item>
			</a-form>
		</div>

		<div class="container">
			<a-table :columns="columns" :scroll="tableScroll" :expanded-row-keys="expandedRowKeys" row-key="id" :data-source="flowSource" :pagination="pagination" :loading="loading" :row-selection="rowSelection" @change="initData" @expanded-rows-change="expandedRowsChange">
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'user_id'">
						<div v-if="record.user != null">{{ record.user.fullname }}</div>
						<div v-else>{{ record.user_id }}</div>
					</template>
					<template v-else-if="column.key === 'status'">
						<flow-status-button :flow-id="record.id" @change="changeFlowStatusData"></flow-status-button>
					</template>

					<template v-else-if="column.key === 'roles'">
						<flowDepartmentButton v-model:roles="itemDepartments[record.id]" v-model:flowId="record.id" @change="flowDepartmentButtonClick"></flowDepartmentButton>
					</template>
					<!-- <template v-else-if="column.key === 'flowStatus'">
						<div>
							<flow-status-button
								:module-id="'flow'"
								:item-id="record.id"
								@change="changeFlowStatusData2"
							></flow-status-button>
						</div>
					</template>-->
					<!-- <template v-else-if="column.key === 'flowDepartments'">
						<div>
							<flowDepartmentButton
								v-model:roles="itemDepartments2[record.id]"
								v-model:flowId="itemFlowId[record.id]"
								@change="flowDepartmentButtonClick"
							></flowDepartmentButton>
						</div>
					</template>-->
					<template v-else-if="column.key === 'operation'">
						<a-space>
							<a-button v-permission="['admin','flow:update']" type="link" :disabled="record.status !== -1" @click="editIndustry(record)">
								<edit-outlined />修改
							</a-button>
							<a-button v-permission="['admin','flow:delete']" type="link" style="color:#ff7875" @click="deleteIndustry(record.id)">
								<delete-outlined />删除
							</a-button>
						</a-space>
					</template>
				</template>
			</a-table>

			<a-modal v-model:visible="visible" :width="700" :title="`${formState.key ? '修改' : '添加'}审批流`" @ok="saveIndustry">
				<a-form ref="formRef" :model="formState" v-bind="{labelCol: { style: { width: '100px' } }}">
					<a-form-item label="名称" name="name" :rules="{required:true, message:'请输入名称'}">
						<a-input v-model:value="formState.name" />
					</a-form-item>
					<!-- 					<a-form-item label="编号" name="no" :rules="{required:true, message:'编号'}">
						<a-input v-model:value="formState.no" />
					</a-form-item>-->
					<!-- 					<a-form-item label="发起人角色" name="initiator_role">
						<a-input v-model:value="formState.initiator_role" />
					</a-form-item>-->
					<a-form-item label="审批类型" name="type_id">
						<a-radio-group v-model:value="formState.type_id" button-style="solid" @change="changeTypeId">
							<a-radio-button v-for="item in flowTypeSource" :key="item.id" :value="item.id">{{ item.name }}</a-radio-button>
						</a-radio-group>
						<!-- 					<a-select v-model:value="formState.type_id" style="width: 120px">
						<a-select-option :value="item.id" v-for="item in flowTypeSource" :key="item.id">{{item.name}}</a-select-option>
						</a-select>-->
					</a-form-item>
					<a-form-item label="模块id" name="module_id" :rules="{required:true, message:'请输入模块id'}">
						<a-input v-model:value="formState.module_id" disabled />
					</a-form-item>
					<a-form-item label="项目id" name="item_id" :rules="{required:true, message:'请输入项目id'}">
						<a-input v-model:value="formState.item_id" />
					</a-form-item>
					<a-form-item label="审批人" name="role_ids" :rules="{required:true, message:'请选择审批人'}">
						<a-checkbox-group v-model:value="role_ids" style="width: 100%" @change="changeDepts">
							<a-row>
								<a-col v-for=" item in roles" :key="item.id" :span="8">
									<a-checkbox :value="item.id">{{ item.name }}</a-checkbox>
								</a-col>
							</a-row>
						</a-checkbox-group>
						<!-- <a-radio-group
							v-model:value="formState.role_ids"
							button-style="solid"
						>
							<a-radio
								v-for="item in roles"
								:key="item.id"
								:value="item.id"
							>{{ item.name }}</a-radio>
						</a-radio-group>-->
					</a-form-item>
					<a-form-item label="审批状态" name="status" :rules="{required:true, message:'选择审批状态'}">
						<a-radio-group v-model:value="formState.status" button-style="solid">
							<a-radio v-for="item in flowStatus" :key="item.status" :value="item.status">{{ item.name }}</a-radio>
							<!-- <a-radio value="-1">拒绝</a-radio> -->
							<!-- <a-radio-button value="d">提交给其他角色</a-radio-button> -->
						</a-radio-group>
					</a-form-item>
					<a-form-item label="备注" name="remark">
						<a-input v-model:value="formState.remark" />
					</a-form-item>
				</a-form>
			</a-modal>
		</div>
		<flowNodeModel ref="flowModel" @change="changeFlowNodeModel"></flowNodeModel>
	</div>
</template>
<script setup>
import { ref, reactive, computed, getCurrentInstance, onMounted, watch } from "vue";
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons-vue";
import router from "../router";
// import flowStatusButton from "@/components/FlowStatusButton";
// import flowDepartmentButton from "@/components/FlowDepartmentButton";
// import flowNodeModel from "@/components/FlowNodeModel";
import { useRoute } from "vue-router";
const route = useRoute();
const { proxy } = getCurrentInstance();

import { post, treeToList } from "../utils";
import { usePagination } from "vue-request";
const flowTypeSource = ref([]);
post("flow/getFlowTypeList", {}).then(({ data }) => {
	flowTypeSource.value = data.map(d => {
		return d;
	});
	// console.log(flowTypeSource)
});
const moduleId = ref();
const itemId = ref();
const searchRef = ref();
const searchState = ref();
searchState.value = { name: "" };
const params = ref();
const role_ids = ref();
const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 250
}));
const flowStatus = ref();
flowStatus.value = [
	{ status: -1, name: "退回" },
	{ status: 0, name: "待审核" },
	{ status: 1, name: "通过" },
	{ status: 2, name: "完成" }
];
const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 120,
		align: "left",
		fixed: "left"
	},
	{
		title: "名称",
		dataIndex: "name",
		sorter: false,
		width: 120,
		ellipsis: true
	},
	{
		title: "发起人",
		dataIndex: "user_id",
		key: "user_id",
		sorter: false,
		width: 120,
		align: "center",
		resizable: true
	},
	{
		title: "状态",
		key: "status",
		sorter: false,
		width: 120,
		resizable: true
		// ellipsis: true
	},
	{
		title: "审批角色",
		key: "roles",
		sorter: false,
		width: 260,
		resizable: true
		// ellipsis: true
	},
	// {
	// 	title: "审批状态【示例】",
	// 	key: "flowStatus",
	// 	sorter: false,
	// 	width: 120,
	// 	resizable: true,
	// },
	// {
	// 	title: "审批流角色【示例】",
	// 	key: "flowDepartments",
	// 	sorter: false,
	// 	width: 260,
	// 	resizable: true,
	// },
	{
		title: "项目ID",
		dataIndex: "item_id",
		sorter: false,
		width: 120,
		align: "center"
	},
	{
		title: "模块",
		dataIndex: "module_id",
		sorter: false,
		width: 120,
		align: "center"
	},
	//自动调节表格剩余宽度
	{},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 240,
		align: "center"
	}
];

// console.log(params.value)
const formRef = ref();
const formState = ref({});
const roles = ref();
const itemDepartments = ref({});
const getDepartments = id => {
	return itemDepartments.value[id] || [];
};
const changeFlowStatusData = e => {
	if (e.act === "flowInfoData") {
		var depts = e.data.flowType.roles;
		itemDepartments.value = {
			...itemDepartments.value,
			[e.data.id]: depts
		};
		// roles.value = e.data.flowType.roles;
	}
};
const itemFlowId = ref({});
const itemDepartments2 = ref({});
const changeFlowStatusData2 = e => {
	if (e.act === "flowInfoData") {
		var depts = e.data.flowType.roles;
		itemDepartments2.value = {
			...itemDepartments2.value,
			[e.data.item_id]: depts
		};
		itemFlowId.value = { ...itemFlowId.value, [e.data.item_id]: e.data.id };
	}
};
const changeFlowNodeModel = ({ act, data }) => {
	// console.log(act);
	// if (e && e.act && ["restData", "updateStatusOk"].indexOf(e.act) > -1) {
	// 	// itemFlowId.value = {};
	// 	// e.data.item
	// 	initData();
	// }
	if (act && ["restData"].indexOf(act) > -1) {
		// if (flowModelRef.value[data.item_id]) {
		// console.log(data);
		// initDepartments(data);
		// initDepartments(data.item_id, data);
		// flowModelRef.value[data.item_id].setData(data);
	}
	// flowModelRef.value[data.item_id].initData();
};
const flowSearch = ref();
flowSearch.value = route.query;
const openStart = ref(0);
const getStatusIds = () => {
	post("flow/getItemIds", {
		module_id: flowSearch.value.flow_module_id,
		status: flowSearch.value.flow_status
	}).then(res => {
		flowSearch.value.ids = res.data.join(",");
		initData();
	});
};
onMounted(() => {
	if (flowSearch.value.status && flowSearch.value.module_id) {
		getStatusIds();
	} else {
		initData();
	}
});

const { data, loading, run, current, pageSize, total } = usePagination(
	param => {
		if (openStart.value === 0) {
			openStart.value = openStart.value + 1;
			return true;
		}
		return post("flow", {
			...param.value,
			...searchState.value
		});
	},
	{
		defaultParams: [
			{
				page_size: 10
			}
		],
		pagination: {
			currentKey: "page",
			pageSizeKey: "page_size",
			totalKey: "total"
		}
	}
);
const initflowTypeSource = (typeid, moduleId) => {
	const data = flowTypeSource.value.map(e => {
		if (e.id === typeid || moduleId === e.module_id) {
			if (e.roles) {
				var depts = e.roles;
				roles.value = depts;
			}
			// params.value.type_id = e.id;
			// params.value.module_id = e.module_id;
			if (!formState.value.name) {
				formState.value.name = e.name;
			}
			formState.value.type_id = e.id;
			formState.value.module_id = e.module_id;
			return e;
		}
	});
};
const changeTypeId = item => {
	const typeid = item.target.value;
	initflowTypeSource(typeid, null);
};
const flowSource = computed(() => data.value?.data || []);

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	// console.log("initData")
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = {
		...filters,
		...searchState
	};

	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};

watch(flowSource, value => {
	const { name } = searchState;
	if (name) expandedRowKeys.value = treeToList(JSON.parse(JSON.stringify(value))).map(d => d.id);

	//删除记录后返回上一页
	if (value.length === 0 && current.value > 1) current.value--;
});

const expandedRowKeys = ref([]);
const expandedRowsChange = e => {
	expandedRowKeys.value = e;
};

const rowSelection = ref();

const visible = ref(false);
const flowModel = ref(null);
const flowDepartmentButtonClick = ({ act, data }) => {
	flowModel.value.showModal({ flowId: data.id });
};
const toDetail = rowid => {
	flowModel.value.showModal({ flowId: rowid });
};
const addIndustry = parentId => {
	formState.value = {
		parent_id: parseInt(parentId) || 0
	};
	visible.value = true;
};
const editIndustry = record => {
	formRef.value?.clearValidate();

	visible.value = true;
	const data = { ...record };
	var dept_ids = data.role_ids;

	if (typeof dept_ids === "string") {
		role_ids.value = dept_ids.split(",").map(d => parseInt(d));
	} else if (typeof dept_ids === "object") {
		role_ids.value = dept_ids;
	}
	// role_ids.value = depts.map((d) => d.role_id);
	initflowTypeSource(data.type_id, data.module_id);
	// console.log(data.role_ids);
	// formState.value = { ...record };
	formState.value = data;
};
const changeDepts = e => {
	if (role_ids.value) formState.value.role_ids = role_ids.value.join(",");
};
const saveIndustry = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			const param = { ...formState.value };
			// if (role_ids.value)
			// 	params.role_ids = role_ids.value.join(",");
			post("flow/save", param)
				.then(() => {
					proxy.$message.success("行业信息提交成功", 1);
					visible.value = false;

					expandedRowKeys.value.push(param.parent_id);

					initData();
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};
const deleteIndustry = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的行业吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("flow/delete", {
				id
			}).then(() => {
				proxy.$message.success("行业删除成功");

				initData();
			});
		}
	});
};

watch(visible, value => {
	if (value) formRef.value?.clearValidate();
});
</script>

<style scoped>
.toolbar {
	padding: 12px;
	background: #fff;
}

.container {
	background: #fff;
	padding: 12px;
}
</style>